import time

from PyQt5.QtCore import QThread, pyqtSignal

import var
from utils.RunBack import Run_FCFS, Run_SSTF, Run_SCAN, Run_CSCAN, Run_Caculate


class CSCANWorker(QThread):
    draw_label_signal = pyqtSignal(list)

    output_signal = pyqtSignal(str)

    def __init__(self, mission, count, direction):
        super(CSCANWorker, self).__init__()
        self.page_requests = mission.copy()
        self.count = count
        self.direction = direction

    def generateOut(self, queue):
        out_str = "方法: CSCAN\n"
        out_str += f"方向{self.direction}\n"
        out_str += f"访问的磁道序列为:\n{queue}\n"
        sum_gap = sum([(abs(queue[i] - queue[i - 1])) for i in range(1, len(queue))])
        out_str += f'移动的磁道数为：{sum_gap}\n'
        out_str += f'平均移动的磁道数为：{sum_gap / self.count}'
        return out_str

    def run(self):
        print("receive run")
        queue_CSCAN = Run_CSCAN(self.page_requests, var.next_id, var.max_id, var.direct)
        out_put = []
        for val in queue_CSCAN:
            out_put.append(val)
            self.draw_label_signal.emit(out_put)
            time.sleep(var.time_split)
        out_put = self.generateOut(queue_CSCAN)

        fcfs_time = Run_Caculate(Run_FCFS(self.page_requests, var.next_id, var.max_id, var.direct))
        sstf_time = Run_Caculate(Run_SSTF(self.page_requests, var.next_id, var.max_id, var.direct))
        scan_time = Run_Caculate(Run_SCAN(self.page_requests, var.next_id, var.max_id, var.direct))
        cscan_time = Run_Caculate(Run_CSCAN(self.page_requests, var.next_id, var.max_id, var.direct))

        self.all_put = f""
        algorithm_times = {
            "FCFS": fcfs_time,
            "SSTF": sstf_time,
            "SCAN": scan_time,
            "CSCAN": cscan_time
        }

        # 按照平均寻道时间对字典进行排序
        sorted_times = sorted(algorithm_times.items(), key=lambda x: x[1])

        # 按照要求的顺序打印算法名称和平均寻道时间
        output = ""
        for algorithm, alg_time in sorted_times:
            output += f"{algorithm} << "

        self.all_put += output[:-3]

        out_put += "\n" + self.all_put
        self.output_signal.emit(out_put)
        print("finish")
